import sys 
import os 
sys.path.append(os.path.abspath("."))    
from flask import Blueprint, jsonify, Response, redirect, request, url_for
from orm import Status, Request,Log
import time

slave = Blueprint('slave', __name__)

# 查询所有空调分机的状态或者增加空调分机
@slave.route('/', methods=['GET', 'POST'])
def all_slave():
    if request.method == 'GET':
        data = [each.__data__ for each in Status.select()]
        return jsonify(data)
    elif request.method == 'POST':
        card_id = request.json['card_id']
        Status(card_id=card_id).save()
        return Response(None, 200)


# 通过身份证id获取从机信息
@slave.route("/check/<card_id>")
def check(card_id):
    data = Status.get(Status.card_id == card_id).__data__
    return jsonify(data)


# 通过slave_id获取单个slave信息
@slave.route("/<id>")
def get_slave(id):
    slave = Status.get(Status.id == id)
    data = slave.__data__
    if data['speed'] != 0:
        data['is_wait']='否'
    else : data['is_wait'] = '是'

    if data['open'] == 1:
        data['is_open']='开'
    else:
        data['is_open'] = '关'
    
    speed_dic = {0:'中风（默认）',1:'低风',2:'中风',3:'高风'}
    data['speed'] = speed_dic[data['speed']]
    return jsonify(slave.__data__)



# slave 设定房间号为id的温度为op度
@slave.route("/temp/<op>/<id>")
def temp_op(op, id):
    op=int(op)
    slave = Status.get(Status.id == id)
    op = min(op,25)
    op = max(18,op)
    try:
        Request(
            slave_id=id, speed=slave.speed,
            temp=op).save()
        return Response(None, 200)
    except Exception as e:
        Request.update({Request.temp:op}).where(Request.slave_id==id).execute()
        return Response(None, 200)
    # finally:
    #     # 生成设置温度请求的详单
    #     Log(slave_id=id,
    #         card_id=slave.card_id,
    #         cur_temp=slave.cur_temp,
    #         target_temp=op,
    #         speed=slave.speed,
    #         req_time=time.strftime('%Y-%m-%d %H:%M:%S')).save()



# slave 设定风速升高/降低一档
@slave.route("/speed/<op>/<id>")
def speed_op(op, id):
    slave = Status.get(Status.id == id)
    op=int(op)
    try:
        Request(
            slave_id=id, speed=op,
            temp=slave.target_temp).save()
        return Response(None, 200)
    except Exception as e:
        Request.update({Request.speed:op}).where(Request.slave_id==id).execute()
        return Response(None, 200)
    finally:
        # 生成设置风速请求的详单
        Log(slave_id=id,
            card_id=slave.card_id,
            cur_temp=slave.cur_temp,
            target_temp=slave.target_temp,
            speed=op,
            req_time=time.strftime('%Y-%m-%d %H:%M:%S')).save()


@slave.route("/shutdown/<id>")
def slave_shutdown(id):
    slave = Status.get(Status.id == id)
    try:
        Request(slave_id=id, speed=0, temp=slave.target_temp).save()
    except:
        Request.update({Request.speed:0}).where(Request.slave_id==id).execute()

    try:
        url = url_for('monitor.close',id=id)
        return redirect(url,code=301)
    except:
            from route.monitor import close
            close(id)

def test():
    print("成功调用！")
